{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    ">https://python.langchain.com/docs/how_to/migrate_agent/\n",
    "\n",
    "This guide assumes familiarity with the following concepts:\n",
    "\n",
    "- [Agents](https://python.langchain.com/docs/concepts/agents/)\n",
    "- [LangGraph](https://langchain-ai.github.io/langgraph/)\n",
    "- [Tool calling](https://python.langchain.com/docs/how_to/tool_calling/)"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "c1358f2ab9a61652"
  },
  {
   "cell_type": "code",
   "outputs": [],
   "source": [
    "from langchain_core.tools import tool\n",
    "import os\n",
    "\n",
    "from dotenv import load_dotenv\n",
    "from langchain_openai import ChatOpenAI\n",
    "\n",
    "load_dotenv()\n",
    "llm = ChatOpenAI(\n",
    "    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key=\"sk-xxx\",\n",
    "    openai_api_key=os.getenv(\"DASHSCOPE_API_KEY\"),\n",
    "    openai_api_base=\"https://dashscope.aliyuncs.com/compatible-mode/v1\",\n",
    "    model_name=\"qwen-max\",\n",
    "    max_retries=0,\n",
    ")\n",
    "\n",
    "\n",
    "@tool\n",
    "def magic_function(input: int) -> int:\n",
    "    \"\"\"Applies a magic function to an input.\"\"\"\n",
    "    return input + 2\n",
    "\n",
    "\n",
    "tools = [magic_function]\n",
    "\n",
    "query = \"what is the value of magic_function(3)?\""
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-10-31T05:55:14.943391Z",
     "start_time": "2024-10-31T05:55:12.904596Z"
    }
   },
   "id": "7127808128f1069a",
   "execution_count": 1
  },
  {
   "cell_type": "markdown",
   "source": [
    "对于LangChain AgentExecutor，我们定义了一个带有代理scratchpad占位符的提示。可以按以下方式调用代理："
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "829f89b3b638c52d"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "{'input': 'what is the value of magic_function(3)?',\n 'output': 'The value of magic_function(3) is 5.'}"
     },
     "execution_count": 2,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langchain.agents import AgentExecutor, create_tool_calling_agent\n",
    "from langchain_core.prompts import ChatPromptTemplate\n",
    "\n",
    "prompt = ChatPromptTemplate.from_messages(\n",
    "    [\n",
    "        (\"system\", \"You are a helpful assistant\"),\n",
    "        (\"human\", \"{input}\"),\n",
    "        # Placeholders fill up a **list** of messages\n",
    "        (\"placeholder\", \"{agent_scratchpad}\"),\n",
    "    ]\n",
    ")\n",
    "\n",
    "agent = create_tool_calling_agent(llm, tools, prompt)\n",
    "agent_executor = AgentExecutor(agent=agent, tools=tools)\n",
    "\n",
    "agent_executor.invoke({\"input\": query})"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-10-31T05:56:07.404602Z",
     "start_time": "2024-10-31T05:56:01.919680Z"
    }
   },
   "id": "d56d4de3bd93acfb",
   "execution_count": 2
  },
  {
   "cell_type": "markdown",
   "source": [
    "**API Reference:**[AgentExecutor](https://python.langchain.com/api_reference/langchain/agents/langchain.agents.agent.AgentExecutor.html) | [create_tool_calling_agent](https://python.langchain.com/api_reference/langchain/agents/langchain.agents.tool_calling_agent.base.create_tool_calling_agent.html) | [ChatPromptTemplate](https://python.langchain.com/api_reference/core/prompts/langchain_core.prompts.chat.ChatPromptTemplate.html)\n",
    "\n",
    "LangGraph的[react代理执行器](https://langchain-ai.github.io/langgraph/reference/prebuilt/#create_react_agent)通过管理一个由消息列表定义的状态来进行操作。它会继续处理该列表，直到代理的输出中没有工具调用。为了启动它，我们输入一个消息列表。输出将包含图的整个状态——在这种情况下，是对话历史。"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "a42e0b96eaedc269"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "{'input': 'what is the value of magic_function(3)?',\n 'output': 'The value of magic_function(3) is 5.'}"
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "from langgraph.prebuilt import create_react_agent\n",
    "\n",
    "langgraph_agent_executor = create_react_agent(llm, tools)\n",
    "\n",
    "messages = langgraph_agent_executor.invoke({\"messages\": [(\"human\", query)]})\n",
    "{\n",
    "    \"input\": query,\n",
    "    \"output\": messages[\"messages\"][-1].content,\n",
    "}\n"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-10-31T05:59:34.020732Z",
     "start_time": "2024-10-31T05:59:31.103125Z"
    }
   },
   "id": "bce3cc226c3b938e",
   "execution_count": 4
  },
  {
   "cell_type": "markdown",
   "source": [
    "**API Reference:**[create_react_agent](https://langchain-ai.github.io/langgraph/reference/prebuilt/#langgraph.prebuilt.chat_agent_executor.create_react_agent)\n",
    "\n",
    "增加会话历史记录"
   ],
   "metadata": {
    "collapsed": false
   },
   "id": "e4d831cfce2611f7"
  },
  {
   "cell_type": "code",
   "outputs": [
    {
     "data": {
      "text/plain": "{'input': 'Pardon?',\n 'output': 'The value of magic_function when applied to the input 3 is 5. In other words, magic_function(3) returns 5. If you need more details on what this function does or how it works, feel free to ask!'}"
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "message_history = messages[\"messages\"]\n",
    "\n",
    "new_query = \"Pardon?\"\n",
    "\n",
    "messages = langgraph_agent_executor.invoke(\n",
    "    {\"messages\": message_history + [(\"human\", new_query)]}\n",
    ")\n",
    "{\n",
    "    \"input\": new_query,\n",
    "    \"output\": messages[\"messages\"][-1].content,\n",
    "}"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "end_time": "2024-10-31T06:00:45.648511Z",
     "start_time": "2024-10-31T06:00:41.138164Z"
    }
   },
   "id": "c4121bbf860ee530",
   "execution_count": 5
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
